package com.skivingcloud.report.datas.service.impl;

import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.skivingcloud.report.datas.entity.ReportDatasetTransform;
import com.skivingcloud.report.datas.service.TransformStrategy;

@Component
public class JsTransformServiceImpl implements TransformStrategy {

	private static Logger log = LoggerFactory.getLogger(JsTransformServiceImpl.class);
	
	private ScriptEngine engine;
    {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript");
    }

	@Override
	public String type() {
		return "js";
	}

	@Override
	public List<JsonNode> transform(ReportDatasetTransform def, List<JsonNode> data) throws Exception {
		return getValueFromJs(def,data);
	}

	private List<JsonNode> getValueFromJs(ReportDatasetTransform def, List<JsonNode> data) throws Exception {
		String js = def.getTransformScript();
        try {
            engine.eval(js);
            if(engine instanceof Invocable){
                Invocable invocable = (Invocable) engine;
                return (List<JsonNode>) invocable.invokeFunction("dataTransform", data);
            }

        } catch (Exception ex) {
            log.info("执行js异常", ex);
            throw ex;
        }
        return null;
    }
}